#!/bin/sh /etc/rc.common
# Copyright (C) 2023 Tianling Shen <cnsztl@immortalwrt.org>

USE_PROCD=0
START=99

CONF="daed-next"
PROG="/usr/bin/dae-wing"
LOG="/var/log/daed-next/daed-next.log"
CRON_FILE="/etc/crontabs/root"
RANDOM_SEED=$RANDOM
RANDOM_NUM=$((RANDOM_SEED % 10 + 1))

setcron() {
  touch $CRON_FILE
  sed -i '/daed-next_sub.sh/d' $CRON_FILE 2>/dev/null
  [ "$(uci -q get daed-next.config.subscribe_auto_update)" -eq 1 ] && echo "${RANDOM_NUM} $(uci -q get daed-next.config.subscribe_update_day_time) * * $(uci -q get daed-next.config.subscribe_update_week_time) /etc/daed-next/daed-next_sub.sh >/dev/null 2>&1" >>$CRON_FILE
  crontab $CRON_FILE
}

delcron() {
  sed -i '/daed-next_sub.sh/d' $CRON_FILE 2>/dev/null
  crontab $CRON_FILE
}

start_service() {
  config_load "$CONF"

  local enabled
  config_get_bool enabled "config" "enabled" "0"
  if [ "$enabled" -eq 0 ]; then
    delcron
    return 1
  fi
  setcron
}

stop_service() {
  delcron
}

service_triggers() {
  procd_add_reload_trigger "$CONF"
}
